package com.qq.weixin.util;

import java.io.Reader;
import java.io.StringReader;
import java.util.HashMap;
import java.util.Map;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

public class XMLConverUtil {

	private static Map<Class<?>, Unmarshaller> uMap = new HashMap<Class<?>, Unmarshaller>();
	private static Map<Class<?>, Marshaller> mMap = new HashMap<Class<?>, Marshaller>();

	public static <T> T convertToObject(Class<T> clazz, String xml) {
		return convertToObject(clazz, new StringReader(xml));
	}

	public static <T> T convertToObject(Class<T> clazz, Reader reader) {
		try {
			if (!uMap.containsKey(clazz)) {
				JAXBContext jaxbContext = JAXBContext.newInstance(clazz);
				Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
				uMap.put(clazz, unmarshaller);
			}
			return (T) uMap.get(clazz).unmarshal(reader);
		} catch (JAXBException e) {
			e.printStackTrace();
		}
		return null;
	}
}
